<?php
//cache functions
function cache_read($file, $dir = '', $mode = '') {
	$file = _get_cache_file($file, $dir);
	if(!is_file($file)) return NULL;
	return $mode ? file_get_contents($file) : include $file;
}

function cache_write($file, $string, $dir = '') {
	if(is_array($string)) {
		$string = "<?php return ".var_export($string, true)."; ?>";
	}
	$file = _get_cache_file($file, $dir);
	$dir = dirname($file);
	if (!is_dir($dir)) mkdir($dir, 0777, true);
	return file_put_contents($file, $string);
}

function cache_delete($file, $dir = '') {
	$file = _get_cache_file($file, $dir);
	return @unlink($file);
}

function _get_cache_file($file, $dir) {
	return ($dir ? DIR_CACHE . $dir.'/'.$file : DIR_CACHE.$file);
}

//shortcuts
function C($key, $value = null) {
	if ($value !== null) $GLOBALS['config']->set($key, $value);
	return $GLOBALS['config']->get($key);
}

function P($key, $default = null) {
	global $request;
	if (isset($request->post[$key])) {
		return v5_trim($request->post[$key]);
	}
	return $default;
}

function G($key, $default = null) {
	global $request;
	if (isset($request->get[$key])) {
		return v5_trim($request->get[$key]);
	}
	return $default;
}

function M($model, $name = null) {
	$GLOBALS['loader']->model($model, $name);
}

function ES($str) {
	return $GLOBALS['db']->escape($str);
}

/**
 * image thumb
 * @param string $file
 * @param int $width
 * @param int $height
 */
function thumb($file = 'no_image.jpg', $width = 100, $height = 100) {
	global $registry;
	if (!$registry->has('model_tool_image')) {
		M('tool/image');
	}
	return $registry->get('model_tool_image')->resize($file, $width, $height);
}

function image_url($image) {
	global $request;
	if (isset($request->server['HTTPS']) && (($request->server['HTTPS'] == 'on') || ($request->server['HTTPS'] == '1'))) {
		return HTTPS_IMAGE . $image;
	} else {
		return HTTP_IMAGE . $image;
	}
}

/**
 * format price with tax
 * @param unknown $price
 * @param unknown $tax_class_id
 * @return boolean
 */
function pprintf($price, $tax_class_id) {
	global $registry;
	
	if (!$price) return false;
	
	if ((C('config_customer_price') && $registry->get('customer')->isLogged()) || !C('config_customer_price')) {
		$price = currency(tax($price, $tax_class_id));
	} else {
		$price = false;
	}
	
	return $price;
}

/**
 * caculate price with tax
 * @param unknown $price
 * @param unknown $tax_class_id
 */
function tax($price, $tax_class_id) {
	global $registry;
	return $registry->get('tax')->calculate($price, $tax_class_id, C('config_tax'));
}

/**
 * currency format
 * @param unknown $price
 * @param string $currency
 * @param string $value
 * @param string $format
 */
function currency($price, $currency = '', $value = '', $format = true) {
	global $registry;
	return $registry->get('currency')->format($price, $currency, $value, $format);
}

/**
 * trim
 * @param mixed $val
 * @return mixed
 */
function v5_trim($val) {
	if (is_array($val)) {
		$result = array();
		foreach($val as $k => $v) {
			$result[$k] = v5_trim($v);
		}
		return $result;
	}
	else return trim($val);
}

/**
 * html_entity_decode
 * @param string $html
 * @return string
 */
function v5_html_entity_decode($html) {
	if (is_array($html)) {
		return array_map('v5_html_entity_decode', $html);
	}
	return html_entity_decode($html, ENT_QUOTES, 'UTF-8');
}

/**
 * short date format
 * @param $date
 * @return string
 */
function v5_date_format($date, $format = null) {
	global $registry;
	!$format && $format = $registry->get('language')->get('date_format_short');
	return date($format, strtotime($date));
}

function v5_date_sub($date1, $date2) {
	$d1 = strtotime($date1 . ' 00:00:00');
	$d2 = strtotime($date2 . ' 00:00:00');
	return ($d1 - $d2) / 3600 / 24 + 1;
}

function rand_string($len = 8) {
	static $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$str = '';
	for ($i=0; $i < $len; $i++)	{
		$str .= substr($chars, mt_rand(0, strlen($chars) -1), 1);
	}
	return $str;
}

function v5_substr($string, $len, $suffix = '...') {
	static $chars = array(' ', ',', '.', '?', ':', ';', '!', ')', '(', '-');
	$l = utf8_strlen($string);
	if ($l <= $len) return $string;
	for ($i = $len - 10; $i < $len + 10; $i++) {
		if ($i > $l - 1 || in_array($string[$i], $chars)) break;
	}
	$i =  ($i > $l - 1) ? $l : $i;
	return utf8_substr($string, 0, $i) . $suffix;
}

/**
 * Get  Greenwich Mean Time
 * @return number
 */
function gmtime() {
	return (time() - date('Z'));
}

function local_date($format) {
	$timezone = C('config_timezone');
	$time = gmtime() + $timezone * 3600;
	return date($format, $time);
}

function local_gettime($timestamp = NULL) {
	$timezone = C('config_timezone');
	if ($timestamp === NULL) {
		$timestamp = time();
	}

	$gmt = $timestamp - date('Z');
	
	return $gmt + ($timezone * 3600);
}

function local_getdate($timestamp = NULL) {
	$timezone = C('config_timezone');

	if ($timestamp === NULL) {
		$timestamp = time();
	}

	$gmt        = $timestamp - date('Z');
	$local_time = $gmt + ($timezone * 3600);

	return getdate($local_time);
}

/**
 * Encrypt
 * @param String $txt
 * @param String $key
 * @return mixed
 */
function encrypt($txt) {
	$rnd = md5(microtime());
	$len = strlen($txt);
	$ren = strlen($rnd);
	$ctr = 0;
	$str = '';
	for($i = 0; $i < $len; $i++) {
		$ctr = $ctr == $ren ? 0 : $ctr;
		$str .= $rnd[$ctr].($txt[$i] ^ $rnd[$ctr++]);
	}
	return str_replace('=', '', base64_encode(kecrypt($str)));
}

/**
 * Dencrypt
 * @param String $txt
 * @param String $key
 * @return mixed
 */
function decrypt($txt) {
	$txt = kecrypt(base64_decode($txt));
	$len = strlen($txt);
	$str = '';
	for($i = 0; $i < $len; $i++) {
		$tmp = $txt[$i];
		$str .= $txt[++$i] ^ $tmp;
	}
	return $str;
}

/**
 * 
 * @param String $txt
 * @param String $key
 * @return String
 */
function kecrypt($txt) {
	$key = md5(C('config_encryption'));
	$len = strlen($txt);
	$ken = strlen($key);
	$ctr = 0;
	$str = '';
	for($i = 0; $i < $len; $i++) {
		$ctr = $ctr == $ken ? 0 : $ctr;
		$str .= $txt[$i] ^ $key[$ctr++];
	}
	return $str;
}

/**
 * check if in range length of a string
 * @param string $str
 * @param int $min
 * @param int $max
 * @return boolean
 */
function range_length($str, $min, $max) {
	$len = utf8_strlen($str);
	return ($len < $min || $len > $max) ? FALSE : TRUE;
}

//html form function
function form_select_option($arr,  $default = NULL,  $use_key = FALSE, $key = NULL, $val = NULL) {
	$html = '';
	
	foreach ($arr as $k => $v) {
		if (is_array($v)) {
			$_k = $use_key ? $k : $v[$key];
			$_v = $v[$val];
		}
		else {
			$_k = $use_key ? $k : $v;
			$_v = $v;
		}
		$selected = !is_null($default) ? (($default == $_k) ? ' selected="selected"' : '') : '';
		$html .= '<option value="' . $_k . '"' . $selected . '>' . $_v . '</option>';
	}
	return $html;
}

function form_radio($arr, $name, $default = NULL) {
	$html = '';
	foreach ($arr as $k => $v) {
		$checked = !is_null($default) ? (($default == $k) ? ' checked="checked"' : '') : '';
		$html .= '<input type="radio" name="'.$name.'" value="'.$k.'"' . $checked . ' />' . $v . "\n";
	}
	return $html;
}

function form_error($key) {
	global $registry;
	if (!$registry->has('form_validation')) {
		return '';
	}
	else return $registry->get('form_validation')->error($key);
}


function delete_files($path, $del_dir = FALSE, $level = 0) {
	// Trim the trailing slash
	$path = rtrim($path, '/');

	if ( ! $current_dir = @opendir($path))
	{
		return FALSE;
	}

	while (FALSE !== ($filename = @readdir($current_dir)))
	{
		if ($filename != "." and $filename != "..")
		{
			if (is_dir($path.'/'.$filename))
			{
				// Ignore empty folders
				if (substr($filename, 0, 1) != '.')
				{
					delete_files($path.'/'.$filename, $del_dir, $level + 1);
				}
			}
			else
			{
				unlink($path.'/'.$filename);
			}
		}
	}
	@closedir($current_dir);

	if ($del_dir == TRUE AND $level > 0)
	{
		return @rmdir($path);
	}

	return TRUE;
}

function get_file_ext($filename) {
	return strtolower(trim(substr(strrchr($filename, '.'), 1)));
}

function send_mail($mail_to, $template_code, $params = array()) {
	global $db;
	$mail_template = $db->queryOne("SELECT subject,content FROM @@mail_template WHERE code='$template_code'");
	if (!$mail_template) return false;
	
	$replace = array(
		'{store_name}' => C('config_name'),
		'{store_url}' => HTTP_CATALOG,
		'{store_address}' => C('config_address'),
		'{store_email}' => C('config_email'),
		'{store_telephone}' => C('config_telephone'), 
	);
	
	$replace = array_merge($replace, $params);
	$subject = str_replace(array_keys($replace), array_values($replace),$mail_template['subject']);
	$content = v5_html_entity_decode($mail_template['content']);
	$content = str_replace(array_keys($replace), array_values($replace),$content);
	
	$mail = new Mail();
	$mail->protocol = C('config_mail_protocol');
	$mail->hostname = C('config_smtp_host');
	$mail->username = C('config_smtp_username');
	$mail->password = C('config_smtp_password');
	$mail->port = C('config_smtp_port');
	$mail->timeout = C('config_smtp_timeout');
	$mail->setTo($mail_to);
	$mail->setFrom(C('config_email'));
	$mail->setSender(C('config_name'));
	$mail->setSubject($subject);
	$mail->setHtml($content);
	$mail->send();
}